<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>WebSocket Client Example</title>
  <script>
    let socket;
    function connectWebSocket() {
      // 创建 WebSocket 连接
      socket = new WebSocket("ws://localhost:17521/socket.io/?EIO=4&transport=websocket");
      // 监听打开事件
      socket.onopen = function(event) {
        console.log("Connected to the WebSocket server.");
        let authData = JSON.stringify({ token: "vue-plugin-hiprint" });
        socket.send("40");
      };
      // 监听消息事件
      socket.onmessage = function(event) {
        let data1 = event.data;
        console.log("Message from server:", data1);
        if (!data1.includes("{") && !data1.includes("[")) {
          setTimeout("echo(2)", 10000)
          return
        }
        let split = data1.split("{");
        let optionalParams = "{"+ split[1];
        console.log("Message from server:", optionalParams, data1);
        let data = JSON.parse(optionalParams);
        if (data.type === "clientInfo") {
          globalThis.clientInfo = data.clientInfo;
          console.log(globalThis.clientInfo);
        } else if (data.type === "printerList") {
          globalThis.printerList = data.printerList;
          console.log(globalThis.printerList);
        }
        setTimeout("echo(2)", 10000)
      };
      // 监听关闭事件
      socket.onclose = function(event) {
        console.log("Connection closed:", event);
      };
      // 监听错误事件
      socket.onerror = function(event) {
        console.error("WebSocket error:", event);
      };
    }
    function echo(count) {
      socket.send(count + 1)
    }
    function sendNews() {
      if (socket && socket.readyState === WebSocket.OPEN) {
        let html = "<h1>Hello World!</h1>";
        let newsData = JSON.stringify(["news", {slient:true, html: html}]);
        socket.send("42" + newsData);
      } else {
        console.log("1", socket.readyState)
        alert("未连接客户端！");
        window.open("hiprint://");
      }
    }
  </script>
</head>
<body>
<h1>WebSocket Client Example</h1>
<button onclick="connectWebSocket()">Connect</button>
<button onclick="sendNews()">Send News</button>
</body>
</html>
